import path from "path";
import { getChildByPath, loadConfigFile } from "../utils";
import { DEFAULT__PLUGIN_DOC_CONFIG_FILES } from "./constant";
import { IPluginData, IPluginDocOptions } from "./interface";
import { readJson } from "fs-extra";

export async function getDirectoryData(
  directoryPaths: string[],
  config: IPluginDocOptions
): Promise<IPluginData[]> {
  const targetData: IPluginData[] = [];
  if (!directoryPaths || directoryPaths.length === 0) {
    return targetData;
  }
  for (let i = 0; i < directoryPaths.length; i++) {
    const pathname = path.join(directoryPaths[i], "./package.json");
    const packageJson = await readJson(pathname, { encoding: "utf8" });
    const { name, version, description, keywords } = packageJson;
    const relativePath = `./${directoryPaths[i].split(process.cwd())[1]}`;
    targetData.push({
      title: description,
      name,
      version,
      pluginType: keywords && keywords[0],
      pluginTag: keywords && keywords[1],
      useType: keywords && keywords[2],
      configPath: path.join(
        relativePath,
        "./public/assets/images/config.png"
      ),
      scenePath: path.join(
        relativePath,
        "./public/assets/images/scene.png"
      ),
    });
  }
  return targetData;
}

/**
 * 生成插件文档
 *
 * @export
 * @param {string} configPath
 * @return {*}  {Promise<void>}
 */
export async function GenaratePluginDoc(configPath: string): Promise<void> {
  // 从解析结果中获取配置
  const config = (await loadConfigFile(
    configPath!,
    DEFAULT__PLUGIN_DOC_CONFIG_FILES
  )) as IPluginDocOptions;
  const packagePath: string = path.resolve(
    path.join(process.cwd(), "./packages")
  );
  // 获取当前包下面的所有文件夹
  const directoryPaths = await getChildByPath(packagePath, false);
  // 获取当前包下面的所有文件夹数据
  const data = await getDirectoryData(directoryPaths, config);
  console.log(data);
}
